package com.hanbang.cxgz_2.view.other;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanbang.cxgz_2.R;
import com.hanbang.cxgz_2.appliction.base.baseadapter.ViewHolder;
import com.hanbang.cxgz_2.appliction.base.baseadapter.recyclerview.CommonAdapter;
import com.hanbang.cxgz_2.appliction.base.baseadapter.recyclerview.click.OnItemClickListener;
import com.hanbang.cxgz_2.appliction.base.view.activity.BaseActivity;
import com.hanbang.cxgz_2.mode.HttpRequest;
import com.hanbang.cxgz_2.mode.httpresponse.other.CityHttpResponse;
import com.hanbang.cxgz_2.mode.javabean.base.CityData;
import com.hanbang.cxgz_2.utils.http.HttpCallBack;
import com.hanbang.cxgz_2.view.widget.CharBar;
import com.hanbang.cxgz_2.view.widget.appbarlayout.SupperToolBar;
import com.hanbang.cxgz_2.view.widget.sticky_recycler.StickyHeadersAdapter;
import com.hanbang.cxgz_2.view.widget.sticky_recycler.StickyHeadersBuilder;
import com.hanbang.cxgz_2.view.widget.sticky_recycler.StickyHeadersItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 城市选择
 * Created by Administrator on 2016/8/27.
 */

public class CitySelectActivity extends BaseActivity   {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.charBar)
    CharBar charBar;
    @BindView(R.id.hint)
    TextView hintTextView;
    @BindView(R.id.searchView)
    SearchView searchView;
    @BindView(R.id.toolbar)
    SupperToolBar toolbar;

    private LinearLayoutManager linearLayoutManager;
    private StickyHeadersItemDecoration stickyHeaderItem;
    private CarBrandHeaderAdapter headerAdapter;
    private List<CityData> listDatas = new ArrayList<>();
    private List<CityData> listDataTotal = new ArrayList<>();

    @BindView(R.id.switchRoot)
    RelativeLayout switchRoot;

    @Override
    public int getContentView() {
        return R.layout.activity_city_select;
    }

    public static void startUI(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, CitySelectActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }


    public static void startUI(Fragment fragment, int requestCode) {
        Intent intent = new Intent(fragment.getContext(), CitySelectActivity.class);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    public void initView() {
        addData();
        setAdapter();
        recyclerView.setFilterTouchesWhenObscured(true);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)) {
                    listDatas.clear();
                    for (int i = 0; i < listDataTotal.size(); i++) {
                        if (listDataTotal.get(i).getCityName().contains(newText)) {
                            listDatas.add(listDataTotal.get(i));
                        }
                    }
                } else {
                    listDatas.clear();
                    listDatas.addAll(listDataTotal);
                }
                charBar.addAllChar(listDatas);
                commonAdapter.notifyDataSetChanged();
                return true;
            }
        });

        toolbar.setBack(this);
    }


    /**
     * 添加城市数据
     */
    private void addData() {

        listDatas.addAll(CityData.getCtiList());
        listDataTotal.addAll(listDatas);

        if (listDatas.size() < 1) {
            getHttpData();
        }
    }

    /**
     * 如果数据没有则连网获取
     */
    public void getHttpData() {
        HttpCallBack.Buider buider = new HttpCallBack.Buider(this).setShowLoadding(true);
        final HttpCallBack httpCallBack = new HttpCallBack<CityHttpResponse>(buider) {
            @Override
            public void onNext(CityHttpResponse result) {
                super.onNext(result);
                //进行data处理
                if (result.getResult() == 0) {
                    ArrayList<CityData> list = new ArrayList<>();
                    list.addAll(result.addPinYin());
                    CityData.saveDb(list);

                    listDatas.addAll(CityData.getCtiList());
                    listDataTotal.addAll(listDatas);
                    commonAdapter.notifyDataSetChanged();
                    charBar.addAllChar(listDatas);
                }
            }
        };
        HttpRequest.getCityData(httpCallBack);
    }


    private void setAdapter() {
        recyclerView.setLayoutManager(linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        stickyHeaderItem = new StickyHeadersBuilder().setAdapter(commonAdapter)
                .setStickyHeadersAdapter(headerAdapter = new CarBrandHeaderAdapter(listDatas), true)
                .setRecyclerView(recyclerView).build();

        recyclerView.addItemDecoration(stickyHeaderItem);

        recyclerView.setAdapter(commonAdapter);
        commonAdapter.notifyDataSetChanged();
        charBar.setHintView(hintTextView);
        charBar.SetOnTouchLetterChangedListener(new CharBar.OnTouchLetterChangedListener() {
            @Override
            public void onTouchLetter(String s) {
                stickyHeaderItem.setSelectPostion(s, linearLayoutManager);
            }
        });
        charBar.addAllChar(listDatas);


        commonAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, View view, Object data, int position) {
                Intent intent = new Intent();
                intent.putExtra("cityId", String.valueOf(listDatas.get(position).getCityID()));
                intent.putExtra("cityName", listDatas.get(position).getCityName());
                setResult(RESULT_OK, intent);
                finish();
            }
        });


    }

    @Override
    public void parseIntent(Intent intent) {

    }


    /**
     * 返回选择数据
     *
     * @param cityName
     */
    private void returnData(String cityName) {

        for (int i = 0; i < listDatas.size(); i++) {
            if (listDatas.get(i).getCityName().contains(cityName)) {
                Intent intent = new Intent();
                intent.putExtra("cityId", String.valueOf(listDatas.get(i).getCityID()));
                intent.putExtra("cityName", listDatas.get(i).getCityName());
                setResult(RESULT_OK, intent);
                finish();
            }
        }


    }

    /**
     * 内容的adapter
     */
    private CommonAdapter<CityData> commonAdapter = new CommonAdapter<CityData>(this, R.layout.item_city_select_content, listDatas) {
        @Override
        public void convert(ViewHolder holder, CityData cityData) {
            holder.setText(R.id.brand, cityData.getCityName());
        }

        @Override
        public long getItemId(int position) {
            return mDatas.get(position).hashCode();
        }
    };

    @OnClick({R.id.activity_city_selectBJ, R.id.activity_city_selectSH, R.id.activity_city_selectGZ, R.id.activity_city_selectShenZ, R.id.activity_city_selectTJ, R.id.activity_city_selectZQ, R.id.activity_city_selectHZ, R.id.activity_city_selectSZ, R.id.activity_city_selectZH, R.id.activity_city_selectXA, R.id.activity_city_selectHEB, R.id.activity_city_selectGM})
    public void onClick(View view) {
        switch (view.getId()) {
            default:
                returnData(((TextView) findViewById(view.getId())).getText().toString());
        }
    }


    /**
     * 左边adapter
     */
    public static class CarBrandHeaderAdapter implements StickyHeadersAdapter<CarBrandHeaderAdapter.ViewHolder> {

        private List<CityData> items;

        public CarBrandHeaderAdapter(List<CityData> items) {
            this.items = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_city_select_header, parent, false);

            return new ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(ViewHolder headerViewHolder, int position) {
            headerViewHolder.title.setText(items.get(position).getInitial());
        }

        @Override
        public long getHeaderId(int position) {
            return items.get(position).getInitial().hashCode();
        }

        public static class ViewHolder extends RecyclerView.ViewHolder {

            TextView title;

            public ViewHolder(View itemView) {
                super(itemView);
                title = (TextView) itemView.findViewById(R.id.zhimu);
            }
        }
    }
}
